package com.org.manhu.chargehelper.Zxing;

import java.io.IOException;
import java.util.Vector;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.Zxing.camera.CameraManager;
import com.org.manhu.chargehelper.Zxing.decoding.CaptureActivityHandler;
import com.org.manhu.chargehelper.Zxing.decoding.InactivityTimer;
import com.org.manhu.chargehelper.Zxing.view.ViewfinderView;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.ui.ExchangeActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.view.SurfaceView;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class CaptureActivity extends Activity implements Callback {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private TextView txtResult;

	// private Button btn_Check;
	// private Button btn_Light;
	private ImageButton backBtn;
	private TextView titleTxt;

	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
		setContentView(R.layout.main);

		AppManager.getAppManager().addActivity(this);

		// 初始化 CameraManager
		CameraManager.init(getApplication());

		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		txtResult = (TextView) findViewById(R.id.txtResult);
		// btn_Check = (Button) findViewById(R.id.btn_Check);
		// btn_Light = (Button) findViewById(R.id.btn_Light);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
		backBtn = (ImageButton) findViewById(R.id.activity_title_back);
		titleTxt = (TextView) findViewById(R.id.activity_title_tv);

		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				CaptureActivity.this.finish();
				turnHandlerExit();
				CaptureActivity.this.finish();
			}
		});

		/*
		 * btn_Check.setOnClickListener(new OnClickListener() { public void
		 * onClick(View v) { // viewfinderView.drawViewfinder();//finder
		 * handler.setState(State.SUCCESS); handler.restartPreviewAndDecode();
		 * // CameraManager.get().requestPreviewFrame( //
		 * handler.getDecodeThread().getHandler(), R.id.decode); System.out
		 * .println("CaptureActivity--->ViewfinderView.setOnclickListener()"); }
		 * });
		 * 
		 * btn_Light.setOnClickListener(new OnClickListener() { public void
		 * onClick(View v) { turnHandler(); } });
		 */
	}

	private Camera camera;

	private void turnHandler() {
		if (camera == null) {
			// camera = Camera.open();
			camera = CameraManager.get().getCamera();
		}
		camera.startPreview();
		Parameters parameters = camera.getParameters();
		// 判断闪光灯当前状态
		if (Parameters.FLASH_MODE_OFF.equals(parameters.getFlashMode())) {
			turnOn(parameters);
		} else if (Parameters.FLASH_MODE_TORCH
				.equals(parameters.getFlashMode())) {
			turnOff(parameters);
		}
	}

	private void turnOn(Parameters parameters) {
		parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
		camera.setParameters(parameters);
		// btn_Light.setText("关闭闪光灯");
	}

	private void turnOff(Parameters parameters) {
		parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
		camera.setParameters(parameters);
		// camera.release();
		// camera = null;
		// btn_Light.setText("开启闪光灯");
	}

	private void turnHandlerExit() {
		if (camera == null) {
			// camera = Camera.open();
			camera = CameraManager.get().getCamera();
		}
		camera.startPreview();
		Parameters parameters = camera.getParameters();
		// 判断闪光灯当前状态
		if (Parameters.FLASH_MODE_OFF.equals(parameters.getFlashMode())) {

		} else if (Parameters.FLASH_MODE_TORCH
				.equals(parameters.getFlashMode())) {
			turnOff(parameters);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		/**
		 * 这里就是一系列初始化相机view的过程
		 */
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		/**
		 * 这里就是看看是否是正常声音播放模式，如果是就播放声音，如果不是，则不播放
		 */
		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		/**
		 * 初始化声音
		 */
		initBeepSound();
		/**
		 * 是否震动
		 */
		vibrate = false;
	}

	@Override
	protected void onPause() {
		super.onPause();
		/**
		 * 关掉相机，关掉解码线程，清空looper队列中message
		 */
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();// 关掉相机
		Log.e("// 关掉相机", "// 关掉相机");
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * 初始化相机
	 */
	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			/**
			 * 新建解码结果handler
			 */
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		/**
		 * 初始化相机
		 */
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	/**
	 * 返回显示的view
	 */
	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	/**
	 * 返回处理解码结果的handler
	 */
	public Handler getHandler() {
		return handler;
	}

	/**
	 * 清空view中先前扫描成功的图片
	 */
	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	public void handleDecode(Result obj, Bitmap barcode) {
		/**
		 * 重新计时
		 */
		inactivityTimer.onActivity();
		/**
		 * 将结果绘制到view中
		 */
		// viewfinderView.drawResultBitmap(barcode);
		/**
		 * 播放jeep声音
		 */
		playBeepSoundAndVibrate();
		/**
		 * 显示解码字符串
		 */
		// txtResult.setText(obj.getBarcodeFormat().toString() + ":" +
		// obj.getText());

		playBeepSoundAndVibrate();

		String scanResult = obj.getText();

		if (scanResult.indexOf("﻿mhbox:exchange") != -1) {
			Intent intent = new Intent(CaptureActivity.this,
					ExchangeActivity.class);
			intent.putExtra("goodsInfo", obj.getText());
			startActivity(intent);
			this.finish();
		} else {
			ToastUtils.showLong(getApplicationContext(), "请扫描兑换商品");
			CaptureActivity.this.finish();
			turnHandlerExit();
			CaptureActivity.this.finish();
		}

		// AlertApp.AlertCheck(CaptureActivity.this, "确定",
		// "扫描到数据",obj.getText());
		// IndexActivity.RESULT_MESSAGE = obj.getBarcodeFormat().toString() +
		// ":" + obj.getText();
		// IndexActivity.RESULT_BITMAP = barcode;

		// Intent intent = new Intent(CaptureActivity.this,
		// IndexActivity.class);
		// this.startActivity(intent);
		// this.finish();
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	/**
	 * 震动时间
	 */
	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		/**
		 * 播放声音
		 */
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		/**
		 * 震动
		 */
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	// turnHandlerExit()
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			showTip();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void showTip() {
		AlertDialog alertDialog = new AlertDialog.Builder(CaptureActivity.this)
				.setTitle("提示").setMessage("确定退出二维码扫描?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						CaptureActivity.this.finish();
						turnHandlerExit();
						CaptureActivity.this.finish();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				}).create(); // 创建对话框
		alertDialog.show(); // 显示对话框
	}

	private void showTips() {
		AlertDialog alertDialog = new AlertDialog.Builder(CaptureActivity.this)
				.setTitle("提示").setMessage("确定退出二维码扫描?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// Intent intent = new Intent();
						// intent.setClass(CaptureActivity.this,
						// IndexActivity.class);//
						// 为当前界面的Activity，Activity2为要跳转的类
						// CaptureActivity.this.startActivity(intent);
						// int pid = android.os.Process.myPid();
						// android.os.Process.killProcess(pid);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				}).create(); // 创建对话框
		alertDialog.show(); // 显示对话框
	}

}